package wiki.hitime.stl.list.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import wiki.hitime.stl.list.bean.dto.ServiceGroup;
import wiki.hitime.stl.list.util.ServiceGroupCacheUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangdaoping
 * @create 2019-08-19 07:58
 */
@Service
@Slf4j
public class ListService {

    @Value("${config.filePath}")
    private String filePath;

    /**
     * 获取服务列表
     *
     * @return 服务列表
     */
    public List<ServiceGroup> load() {
        List<ServiceGroup> serviceGroupList = ServiceGroupCacheUtils.get();
        if (CollectionUtils.isEmpty(serviceGroupList)) {
            serviceGroupList = loadByFile();
        }
        return serviceGroupList;
    }

    /**
     * 从文件加载服务列表
     *
     * @return 服务列表
     */
    public List<ServiceGroup> loadByFile() {
        File file = new File(filePath);
        List<ServiceGroup> serviceGroupList = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(file)) {
            byte[] fileByte = new byte[100];
            StringBuilder stringBuilder = new StringBuilder();
            int length;
            while ((length = inputStream.read(fileByte)) != -1) {
                stringBuilder.append(new String(fileByte, 0, length));
            }
            log.info(stringBuilder.toString());
            List<ServiceGroup> fileServiceGroupList = JSON.parseObject(stringBuilder.toString(), new TypeReference<List<ServiceGroup>>() {
            });
            if (!CollectionUtils.isEmpty(fileServiceGroupList)) {
                serviceGroupList.addAll(fileServiceGroupList);
            }
        } catch (IOException e) {
            log.error("文件读取失败，filePath={}", filePath);
        }
        ServiceGroupCacheUtils.set(serviceGroupList);
        return ServiceGroupCacheUtils.get();
    }
}
